﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;

namespace CryptoLogo
{
	public partial class LogoForm : Form
	{
		public LogoForm()
		{
			InitializeComponent();

			this.PopulateSaveDialogExtentions();
		}

		private void PopulateSaveDialogExtentions()
		{
			StringBuilder filter = new StringBuilder();

			foreach (ImageFormat format in this.AcceptedFormats)
			{
				filter.Append(format.GetFileDialogFilter());
			}

			filter.Remove(filter.Length - 1, 1);

			this.saveFileDialog.Filter = filter.ToString();
		}

		private void drawButton_Click(object sender, EventArgs e)
		{
			ImageGenerator generator = new ImageGenerator();
			generator.Origin = new PointF((float)this.originXNumericUpDown.Value, (float)this.originYNumericUpDown.Value);
			generator.EdgeLength = (float)this.edgeLengthNumericUpDown.Value;
			generator.Alpha = (float)this.angleNumericUpDown.Value;

			this.displayPictureBox.Image = generator.GenerateImage();
		}

		

		private void saveButton_Click(object sender, EventArgs e)
		{
			if (this.saveFileDialog.ShowDialog() == DialogResult.OK)
			{
				string filename = this.saveFileDialog.FileName;
				
				// Get the output format based off of the selected extention filter
				ImageFormat format = this.AcceptedFormats[this.saveFileDialog.FilterIndex-1]; 
				this.displayPictureBox.Image.Save(filename, format);

				////	Read back to test the image format
				//Image test = Image.FromFile(this.saveFileDialog.FileName);
				//MessageBox.Show("The file was saved as a " + this.GetRawTypeName(test));
			}	
		}

		/// <summary>
		/// These are the formats we use to save the image
		/// </summary>
		private ImageFormat[] acceptedFormats;
		private ImageFormat[] AcceptedFormats
		{
			get
			{
				if (acceptedFormats == null)
				{
					List<ImageFormat> formats = new List<ImageFormat>();

					formats.Add(ImageFormat.Png);
					formats.Add(ImageFormat.Jpeg);
					formats.Add(ImageFormat.Gif);
					formats.Add(ImageFormat.Bmp);

					acceptedFormats = formats.ToArray();
				}

				return acceptedFormats;
			}
		}

		private string GetRawTypeName(Image image)
		{
			string name = "unknown";

			foreach (ImageFormat format in this.AcceptedFormats)
			{
				if (image.RawFormat.Equals(format))
				{
					name = format.ToString();
				}
			}

			return name;
		}
	}

	public static class Extentions
	{
		public static string GetFileDialogFilter(this ImageFormat imageFormat)
		{
			string filter = String.Format(
				"{0} Image (*.{1})|*.{1}|",
				imageFormat.ToString().ToUpper(), imageFormat.ToString().ToLower());

			return filter;
		}


	}
}
